﻿/**
* File: age.ui.qna.category.js 
* Author: Angelo Gomez
* Date: 2011.09.08
*
* Copyright (c) 2011 Angelo Gomez
* 
*/
/// <reference path="jquery-1.5.1-vsdoc.js" />

(function ($) {

	var _getCategoryDataUrl = '/Category/Index';
	var _categoryCheckbox = 'categoryID';
	var _categoryTitleText = 'Categories';

	var _categoryModel = { Resultset: [
			{ Category: 'Category 1', CategoryID: 0, Description: '', ParentID: 0 },
			{ Category: 'Category 2', CategoryID: 0, Description: '', ParentID: 0 },
			{ Category: 'Category 3', CategoryID: 0, Description: '', ParentID: 0 }
		]
	};

	/// $(selector).displayCategorySelectionPanel(options);
	/// is: A function that renders HTML of the categories.
	/// gets: options (Object)
	///				>> dimensionUnit (string): Unit of measure for column size, enter '%' or 'px' or 'em' or any other unit, default: 'px'
	///				>> width (int): the width of each column. Unit depends on dimensionUnit. default: 250
	///				>> cols (int): number of columns
	///				>> parentContainer (string): selector of container that columns and data will be appended to
	///				>> indent (int): number of spaces for the children categories. default: 2
	///				>> debug (bool): properties activated for debugging. default: false
	///				>> titleText (string): Text of the section title.
	/// returns: None. 
	$.fn.displayCategorySelectionPanel = function (options) {

		var defaults = {
			dimensionUnit: 'px',
			width: 250,
			cols: 2,
			parentContainer: '#categoryMainContainer',
			indent: 2,
			titleText: 'Categories',
			debug: false
		};

		// Bind the properties:
		var options = $.extend(defaults, options);

		// Parse the parentContainer string selector
		var parentcontainer = options.parentContainer;
		if (parentcontainer.substring(0, 1) != '#') parentcontainer = '#' + options.parentContainer;

		// Create title text
		var categoryTitleText = document.createElement('div');
		$(categoryTitleText).addClass('qContainer')
				.html('<h2>' + options.titleText + '</h2><span id="categoryInstruction"><span>')
				.insertBefore(parentcontainer)
				.hide()
				.show('slow');

		// get category data
		var categoryData = eval($(document).getCategoryData(0));

		if (categoryData != undefined) {
			$(parentcontainer).empty();
		}

		$(parentcontainer).css('float', 'left');

		if (options.debug) $(parentcontainer).css('border', '1px solid #ccc');

		//format CategoryData and render to the container
		var formattedCategoryData = renderCategoryTexts(categoryData, 0, options.indent, true);

		// append categoryData to the dataHolder
		var tmpHolder = document.createElement('div');
		$(tmpHolder).addClass('categoryCol')
				.attr('id', 'categoryDataHolder')
				.html(formattedCategoryData)
				.appendTo(parentcontainer)
				.hide();

		var modelPerColCount = Math.ceil($(parentcontainer + ' div').size() / options.cols);
		var colWidth = options.width + options.dimensionUnit; // Math.floor(100 / options.cols);


		for (var i = 0; i < options.cols; i++) {

			// Create a div
			var col = document.createElement('div');
			$(col).addClass('categoryCol')
				.attr('id', 'categoryCol' + i)
				.appendTo(parentcontainer)
				.hide();

			$(col).width(colWidth);
			$(col).css('float', 'left');
			if (options.debug) $(col).css('border', '1px solid #f00');

			// Transfer the divs from tmpHolder to col:
			$(tmpHolder).children('div').each(function (index) {
				if (index <= modelPerColCount) {
					$(this).appendTo(col);
					if (options.debug) $(this).css('border', '1px solid #00f');
				}
			});

			$(col).show('slow');
		}
		return;
	}

	/// var objectEntity = $(selector).getCategoryData(parentID);
	/// is: A function that retrieves data from the WS bridge and returns as XML or object.
	/// gets: parentId (int): Parent ID of the category children to be retrieved.
	/// returns: Object. CategoryTreeEntity[] object.
	$.fn.getCategoryData = function (parentId) {

		var d = $.ajax({
			url: "/Category/CategoryTreeData",
			type: 'POST',
			dataType: 'json',
			data: {},
			async: false,
			success: function (result) {
			},
			error: function (d) {
				alert('Get categories failed.');
			}
		});

		return eval(d.responseText);
	}

	/// var returnsString = renderCategoryTexts(data, startAt, indent, showCheckbox);
	/// is: A function that returns formatted elements containing the category data.
	/// gets:	>> data (CategoryTreeEntity[]): The array of CategoryTreeEntity.
	///				>> startAt (int): What position to start each of the root category. Usually at 0;
	///				>> indent (int): Number of spaces to indent to display children.
	///				>> showCheckbox (bool): Show checkboxes before the text.
	/// returns: String. Formatted HTML ready to rendered inside a container.
	var renderCategoryTexts = function (data, startAt, indent, showCheckbox) {

		// Default indent to 2 if indent data is NaN.
		if (indent == NaN) indent = 2;

		// Instantiate return string to an empty string.
		var returnString = '';

		if (data.length > 0) {

			for (var i = 0; i < data.length; i++) {

				var spacing = '';
				var addIndent = 0;
				if (startAt != 0) {
					for (var d = 0; d < indent; d++) {
						spacing += '&nbsp';
						addIndent++;
					}
				}
				returnString += '<div>';
				var categoryCheckboxHtml = '';
				if (showCheckbox) categoryCheckboxHtml = '<input type="checkbox" name="' + _categoryCheckbox + '" id="' + _categoryCheckbox + '" value="' + data[i].categoryID + '" class="qCheckbox" />';

				returnString += spacing + categoryCheckboxHtml + data[i].categoryText + '';

				returnString += '</div>';

				if (data[i].children.length > 0) {
					returnString += renderCategoryTexts(data[i].children, startAt + 1, indent + addIndent, showCheckbox);
				}
			}
		}

		return returnString;
	}


})(jQuery);
